package com.haiyi.activiti.engine.framework.cglib;

import com.haiyi.activiti.engine.util.Assert;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * <p> </p>
 *
 * <pre> Created: 2018/12/10 14:40 </pre>
 *
 * @author hlu
 * @version 1.0
 * @since JDK 1.7
 */
public class DefaultCglibMethodInterceptor<T> extends CglibMethodInterceptor<T> {

    private MethodFilter methodFilter;
    private MethodCallBack methodCallBack;

    public DefaultCglibMethodInterceptor(T target,MethodFilter methodFilter,MethodCallBack methodCallBack) {
        super(target);
        Assert.isNotNull(methodFilter,"methodFilter不允许为空值！");
        this.methodFilter = methodFilter;
        this.methodCallBack = methodCallBack;
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {

        //不拦截Object类方法
        if (Object.class.equals(method.getDeclaringClass())) {
            return methodProxy.invokeSuper(target, args);
        }

        if(methodFilter.doWith(obj, method, args, methodProxy)){
            if(methodCallBack!=null){
                methodCallBack.callBackBefore(obj, method, args, methodProxy);
            }
            final Object o = methodProxy.invokeSuper(target, args);
            if(methodCallBack!=null){
                methodCallBack.callBackAfter(obj, method, args, methodProxy,o);
            }
            return o;
        }

        return methodProxy.invokeSuper(target,args);
    }
}
